import { Checkbox, Input, Select } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import type { CustomReportField } from "./entity";

import dictService from "@/api/services/system/dictService";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import type { Dict } from "#/entity";

interface ReportFieldProps {
	loading: boolean;
	fieldList: CustomReportField[];
	setFieldList: React.Dispatch<React.SetStateAction<CustomReportField[]>>;
}

const CustomReportFieldPage: React.FC<ReportFieldProps> = ({ loading, fieldList, setFieldList }) => {
	const [dictOptions, setDictOptions] = useState<Dict[]>([]);

	const getFieldColumns = (
		handleFieldChange: (id: React.Key, field: string, value: any) => void,
	): ColumnsType<CustomReportField> => [
		{
			title: "字段名",
			key: "fieldName",
			dataIndex: "fieldName",
		},
		{
			title: "字段描述",
			key: "fieldComment",
			dataIndex: "fieldComment",
			render: (text, record) => (
				<Input value={text} onChange={(e) => handleFieldChange(record.id, "fieldComment", e.target.value)} />
			),
		},
		{
			title: "字段类型",
			key: "fieldType",
			dataIndex: "fieldType",
			width: 120,
		},
		{
			title: "是否显示",
			key: "isVisible",
			dataIndex: "isVisible",
			width: 80,
			render: (text, record) => (
				<Checkbox
					checked={text === 1}
					onChange={(e) => handleFieldChange(record.id, "isVisible", e.target.checked)}
				/>
			),
		},
		{
			title: "是否查询",
			key: "isQuery",
			dataIndex: "isQuery",
			width: 80,
			render: (text, record) => (
				<Checkbox checked={text === 1} onChange={(e) => handleFieldChange(record.id, "isQuery", e.target.checked)} />
			),
		},
		{
			title: "字典编码",
			key: "dictCode",
			dataIndex: "dictCode",
			render: (text, record) => (
				<Select
					value={text}
					allowClear
					dropdownStyle={{ minWidth: 200 }}
					style={{ width: "100%" }}
					onChange={(value) => handleFieldChange(record.id, "dictCode", value)}
					options={dictOptions.map((item) => ({
						value: item.dictCode,
						label: item.dictName,
					}))}
					optionRender={(option) => (
						<div>
							<span>{option.label}</span>
							<span style={{ color: "#999", marginLeft: 15 }}>{option.value}</span>
						</div>
					)}
				/>
			),
		},
	];

	// 处理字段变更
	const handleFieldChange = (id: React.Key, field: string, value: any) => {
		// 如果是checkbox的值，将布尔值转换为数字值（true为1，false为0）
		const processedValue = typeof value === "boolean" ? (value ? 1 : 0) : value;
		setFieldList((prevData) => prevData.map((item) => (item.id === id ? { ...item, [field]: processedValue } : item)));
	};

	// 获取字段列配置
	const fieldColumns = getFieldColumns(handleFieldChange);

	// 获取所有字典信息
	const getDictOptions = async () => {
		dictService
			.listAll()
			.then((res) => {
				setDictOptions(res);
			})
			.catch((error) => {
				console.error("获取字典失败:", error);
				toast.error("获取字典失败:");
			});
	};

	useEffect(() => {
		getDictOptions();
	}, []);

	return (
		<>
			<Table
				rowKey="id"
        size="small"
				loading={loading}
				pagination={false}
				columns={fieldColumns}
				dataSource={fieldList}
        scroll={{
          y: 200, // 固定高度，触发垂直滚动
        }}
			/>
		</>
	);
};

export default CustomReportFieldPage;
